﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NT40Redis.Models;

using Microsoft.Extensions.Caching;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.AspNetCore.Http;
namespace NT40Redis.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            //向session中保存数据
            HttpContext.Session.SetString("mysession",$"你好，张三{DateTime.Now}");
            ViewBag.Msg = "数据添加到session成功";
            //读session中保存的数据
            ViewBag.Msg1= "从session中读取到的数据"+HttpContext.Session.GetString("mysession");

            //创建访问操作
            RedisCacheOptions options = new RedisCacheOptions();
            //options.Configuration = "127.0.0.1:6379,aboutConnert=false";
            //连接字符串
            options.Configuration = "127.0.0.1:6379";
            //创建实例
            options.InstanceName = "myredis";
            //创建客户端对象
            var redisClient = new RedisCache(options);
            //向redis中写入数据
            //不设置过期时间
            redisClient.SetString("mysession", HttpContext.Session.GetString("mysession"));
            ////设置绝对过期时间
            //redisClient.SetString("name2", $"李四{DateTime.Now}",
            //    new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddMinutes(2)));
            ////设置相对过期时间
            //redisClient.SetString("name3", $"王五！{DateTime.Now}",
            //    new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(2)));
            

            return View();
        }

        public IActionResult Privacy()
        {
            RedisCacheOptions options = new RedisCacheOptions();
            options.Configuration = "127.0.0.1:6379";
            options.InstanceName = "myredis";

            var redisClient = new RedisCache(options);

            //读取数据
            string result = redisClient.GetString("name1");
            ViewBag.Msg1 = "数据1：" + result;
            result = redisClient.GetString("name2");
            ViewBag.Msg2 = "数据1：" + result;
            result = redisClient.GetString("name3");
            ViewBag.Msg3 = "数据1：" + result;
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
